package com.clf.springBoot.filter;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.core.net.SyslogOutputStream;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



@WebFilter(filterName = "paramFilter",urlPatterns = "/*")
public class ParamFilter implements Filter {
    public final static Logger LOGGER= LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       LOGGER.debug("==========Init Param Filter======");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        LOGGER.debug("==========Do Param Filter======");


        HttpServletRequest requ=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        HttpServletRequestWrapper requestWrapper=new HttpServletRequestWrapper(requ){
            @Override
            public String getParameter(String name) {
                String value=requ.getParameter(name);
                return StringUtils.isBlank(value)?value:value.toLowerCase().replaceAll("fuck","****");
            }

            @Override
            public String[] getParameterValues(String name) {
                List<String> values = new ArrayList<>();
                String [] temp=super.getParameterValues(name);
                return Arrays.asList(temp).stream()
                        .map(item -> item.toLowerCase().replaceAll("fuck","****"))
                        .toArray(String[]::new);
            }
        };
        filterChain.doFilter(requestWrapper, resp);
    }

    @Override
    public void destroy() {

        LOGGER.debug("==========Destroy Param Filter======");
    }
}
